#include <udp_sender.hpp>

UdpSender::UdpSender(const char* ip, int port)
	: m_SocketId(0)
	, m_SizeSend(0)
	, m_DataSeqSend(0)
	, m_DataTypeSend(0)
{
	m_BuffSend = (char*)malloc(BUFF_FIFO_SIZE);

#if WIFI_AP_ENABLE || WIFI_STA_ENABLE

	// 创建socket
	if ((m_SocketId = socket(AF_INET, SOCK_DGRAM, 0)) < 0)
	{
		LOG("socket creation failed");
		return;
	}

	memset(&m_ServAddr, 0, sizeof(struct sockaddr_in));

	// 填充服务器信息
	m_ServAddr.sin_family = AF_INET;
	m_ServAddr.sin_port	  = htons(port);

	// 将IPv4地址从文本转换成二进制形式
	if (inet_pton(AF_INET, ip, &m_ServAddr.sin_addr) <= 0)
	{
		LOG("Invalid address/ Address not supported\n");
		return;
	}

	LOG("UpdSender startup ip %s port %d.\n", ip, port);
#endif
}

UdpSender::~UdpSender()
{
	free(m_BuffSend);
}

void UdpSender::SendData(uint16_t dataType, char* data, int size)
{
#if WIFI_AP_ENABLE || WIFI_STA_ENABLE
	if (data == nullptr || size <= 0)
	{
		return;
	}

#if 0
	printf("udp send: ");
	for (int i = 0; i < size; i++)
	{
		printf("%02x ", (uint8_t)data[i]);
	}
	printf("\n");
#endif

	m_DataTypeSend = dataType;
	m_DataSeqSend++;
	m_Protocol.Pack(m_BuffSend, &m_SizeSend, data, size, m_DataSeqSend, m_DataTypeSend);
	if (m_SizeSend > 0 && m_SizeSend < BUFF_FIFO_SIZE)
	{
		// 发送数据
		sendto(m_SocketId, (const char*)m_BuffSend, m_SizeSend, 0, (const struct sockaddr*)&m_ServAddr, sizeof(struct sockaddr_in));
	}
#endif
}
